# 注意,本页面在程序中动态创建
# coding: utf-8

import json
import requests
from PyQt5 import QtCore
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout, QLabel
from PyQt5.QtCore import Qt, QUrl
from PyQt5.QtGui import (
    QIcon,
    QImage,
    QPixmap,
    QFont,
    QFontMetrics,
    QPainter,
    QPainterPath,
)
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest

from psutil import users
from qfluentwidgets import (
    TransparentPushButton,
    PrimaryPushButton,
    SmoothScrollArea,
    FluentIcon,
    ToolTipFilter,
    ToolTipPosition,
)

from app.components.commentCard import CommentCard
from app.ui_controller.ui_pool import Portal_Pool, Ui_Pool
from app.common.get_comment import GetCommentThread
from app.common.setting import PURCHASED


class CommentListScrollArea(SmoothScrollArea):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.widgets = QWidget(self)

        self.__initWidget()

    def __initWidget(self):
        self.setObjectName("CommentListScrollArea")
        self.setWidgetResizable(True)
        self.setMinimumHeight(250)
        self.setWidget(self.widgets)
        self.setStyleSheet(
            "#CommentListScrollArea{" "background:transparent;" "border:none;" "}"
        )

        self.widgets.setObjectName("CommentListScrollAreaWidget")
        self.widgets.setStyleSheet(
            "#CommentListScrollAreaWidget{" "background:transparent;" "}"
        )

        self.__initLayout()

    def __initLayout(self):
        self.layouts = QVBoxLayout(self.widgets)
        self.layouts.setContentsMargins(0, 0, 0, 0)
        self.widgets.setLayout(self.layouts)

    def addCommentCard(self, url, nickName, comment, time):
        card = CommentCard(self, url, nickName, comment, time)
        self.layouts.addWidget(card, 0, Qt.AlignmentFlag.AlignTop)


class ResourceDetailsInterface(SmoothScrollArea):
    def __init__(
        self,
        coverPicture: QPixmap,
        resourceTitle: str,
        resourceAuthor: dict,
        resourceId: int,
        resourceRenewalTime: str,
        resourceSummary: str,
        parent=None,
    ):
        """
        __init__ 资源详情页面

        Args:
            coverPicture (QPixmap): 资源卡片图片
            resourceTitle (_type_): 资源标题
            resourceAuthor (_type_): 资源作者名称
            resourceId (_type_): 资源ID
            resourceRenewalTime (_type_): 资源更新时间
            resourceSummary (str): 资源描述
        """
        super().__init__(parent=parent)
        self.widgets = QWidget(self)

        self.coverPicture: QPixmap = coverPicture
        self.resourceTitle: str = resourceTitle
        self.resourceAuthor: dict = resourceAuthor
        self.resourceId: int = resourceId
        self.resourceRenewalTime: str = resourceRenewalTime
        self.resourceSummary: str = resourceSummary

        self.backButton = TransparentPushButton(self)
        self.resourceTitleLabel = QLabel(self)
        self.resourceRenewalTimeLabel = QLabel(self)
        self.installButton = PrimaryPushButton(self)
        self.resourceCoverPictureLabel = QLabel(self)
        self.authorAvatarLabel = QLabel(self)
        self.authorNickNameLabel = QLabel(self)
        self.authorShipLabel = QLabel(self)
        self.resourceSummaryLabel = QLabel(self)
        self.resourceCommentArea = CommentListScrollArea(self)

        self.__initWidget()
        self._loadImage(self.resourceAuthor["Avatar"])
        self._loadComments()

    def __initWidget(self):
        self.setWidgetResizable(True)
        self.setWidget(self.widgets)
        self.setObjectName("resourceDetailsInterface")
        self.setStyleSheet("background:transparent;" "border:none;")
        self.widgets.setObjectName("InfoScrollAreaWidget")
        self.widgets.setStyleSheet("background:transparent;")

        self.backButton.setText(self.tr("Back"))
        self.backButton.setIcon(FluentIcon.LEFT_ARROW)
        self.backButton.clicked.connect(self._back)

        self.resourceTitleLabel.setText(self.resourceTitle)
        self.resourceTitleLabel.setMinimumWidth(500)
        self.resourceTitleLabel.setFont(self._setFont("HarmonyOS Sans SC", 25))
        # 设置资源标题自动隐藏
        fontWidth = QFontMetrics(self.resourceTitleLabel.font())
        elideNote = fontWidth.elidedText(
            self.resourceTitle, Qt.ElideRight, self.resourceTitleLabel.width()
        )
        self.resourceTitleLabel.setText(elideNote)
        self.resourceTitleLabel.setToolTip(self.resourceTitle)
        self.resourceTitleLabel.installEventFilter(
            ToolTipFilter(self.resourceTitleLabel, 0, ToolTipPosition.BOTTOM)
        )

        self.resourceRenewalTimeLabel.setText(self.resourceRenewalTime)
        self.resourceRenewalTimeLabel.setFont(self._setFont("HarmonyOS Sans SC", 10))
        self.resourceRenewalTimeLabel.setStyleSheet("color: #B6B6B6")

        self.installButton.setText(self.tr("Download"))
        self.installButton.setIcon(FluentIcon.DOWNLOAD)
        self.installButton.clicked.connect(self._downLoadFile)

        # self.resourceCoverPictureLabel.setPixmap(self.coverPicture)
        self.resourceCoverPictureLabel.setFixedSize(352, 198)
        self._setRoundedImage(self.resourceCoverPictureLabel, self.coverPicture, 8)
        self.resourceCoverPictureLabel.setScaledContents(True)

        self.authorAvatarLabel.setScaledContents(True)
        self.authorAvatarLabel.setFixedSize(40, 40)

        self.authorNickNameLabel.setText(self.resourceAuthor["Name"])
        self.authorNickNameLabel.setFont(self._setFont("HarmonyOS Sans SC", 12))

        self.authorShipLabel.setText("资深作者")
        self.authorShipLabel.setFont(self._setFont("HarmonyOS Sans SC", 10))
        self.authorShipLabel.setStyleSheet("color: #B6B6B6")

        self.resourceSummaryLabel.setWordWrap(True)
        self.resourceSummaryLabel.setText(self.resourceSummary)
        self.resourceSummaryLabel.setFont(self._setFont("HarmonyOS Sans SC", 12))

        self.__initLayout()

    def __initLayout(self):
        self.layouts = QVBoxLayout(self.widgets)
        # self.layouts.setContentsMargins(0, 0, 0, 0)
        self.widgets.setLayout(self.layouts)
        self.layouts.setSpacing(0)
        self.layouts.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.resourceTitleTimeLayout = QVBoxLayout()
        self.resourceInstallLayout = QHBoxLayout()
        self.avatarLayout = QHBoxLayout()
        self.avatarLayout.setAlignment(Qt.AlignmentFlag.AlignLeft)
        self.avatarNameLayout = QVBoxLayout()
        self.avatarNameLayout.setSpacing(0)

        self.layouts.addWidget(
            self.backButton, 0, Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft
        )

        self.resourceTitleTimeLayout.addWidget(self.resourceTitleLabel)
        self.resourceTitleTimeLayout.addWidget(self.resourceRenewalTimeLabel)

        self.resourceInstallLayout.addLayout(self.resourceTitleTimeLayout)
        self.resourceInstallLayout.addWidget(
            self.installButton,
            0,
            Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignRight,
        )
        self.layouts.addLayout(self.resourceInstallLayout)

        self.layouts.addSpacing(5)
        self.layouts.addWidget(
            self.resourceCoverPictureLabel,
            0,
            Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft,
        )

        self.avatarNameLayout.addWidget(self.authorNickNameLabel)
        self.avatarNameLayout.addWidget(
            self.authorShipLabel, 0, Qt.AlignmentFlag.AlignTop
        )
        self.avatarLayout.addWidget(
            self.authorAvatarLabel,
            0,
            Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
        )
        self.avatarLayout.addSpacing(10)
        self.avatarLayout.addLayout(self.avatarNameLayout)
        self.layouts.addSpacing(5)
        self.layouts.addLayout(self.avatarLayout)

        self.layouts.addSpacing(5)
        self.layouts.addWidget(
            self.resourceSummaryLabel,
            0,
            Qt.AlignmentFlag.AlignTop,
        )

        self.layouts.addSpacing(5)
        self.layouts.addWidget(
            self.resourceCommentArea,
            0,
        )

    def _setFont(self, fontFamily, fontSize):
        font = QFont()
        font.setFamily(fontFamily)
        font.setPointSize(fontSize)
        return font

    def _setRoundedImage(self, label, pixmap, radius):
        pixmap = pixmap.scaled(
            label.size(), Qt.AspectRatioMode.KeepAspectRatioByExpanding
        )

        rounded_pixmap = QPixmap(pixmap.size())
        rounded_pixmap.fill(Qt.transparent)

        painter = QPainter(rounded_pixmap)
        painter.setRenderHint(QPainter.Antialiasing)
        path = QPainterPath()
        path.addRoundedRect(0, 0, pixmap.width(), pixmap.height(), radius, radius)
        painter.setClipPath(path)
        painter.drawPixmap(0, 0, pixmap)
        painter.end()

        label.setPixmap(rounded_pixmap)
        label.setScaledContents(True)

    # 网络线程加载图片
    # TODO: 优化流程
    def _loadImage(self, url):
        # 创建QNetworkAccessManager实例
        self.manager = QNetworkAccessManager(self)
        # 连接信号
        self.manager.finished.connect(self._imageLoaded)

        # 创建QNetworkRequest
        request = QNetworkRequest(QUrl(url))

        # 发送GET请求
        self.manager.get(request)

    def _imageLoaded(self, reply):
        # 检查请求是否成功
        if reply.error() == QNetworkReply.NoError:
            # 将网络回复转换为QImage
            image = QImage()
            image.loadFromData(reply.readAll())
            # 将QImage转换为QPixmap并设置到QLabel
            self._setRoundedImage(self.authorAvatarLabel, QPixmap.fromImage(image), 20)
        else:
            self._setRoundedImage(
                self.authorAvatarLabel, QPixmap(":app/images/defaultAvatar.jpg"), 20
            )

    def _back(self):
        main_pool: Ui_Pool = Portal_Pool.portals["main_pool"]
        win = main_pool.find_object_byName("win")
        win.navigationInterface.removeWidget(f"tempInterface_{self.resourceId}")

    def _loadComments(self):
        getCommentThread = GetCommentThread(self.resourceId)
        getCommentThread.commentsInfo.connect(
            lambda x: self.resourceCommentArea.addCommentCard(
                x["authorAvatar"], x["authorNickname"], x["content"], x["updatedAt"]
            )
        )
        getCommentThread.start()
        getCommentThread.wait()

    def _downLoadFile(self):
        userInformation = Portal_Pool.portals["user"]
        userToken = userInformation["data"]["token"]
        header = {"token": userToken}
        jsons = {"resourceId": self.resourceId, "type": "RESOURCE"}
        r = requests.post(PURCHASED, json=jsons, headers=header)
        result = json.loads(r.text)
        if result["code"] == 200:
            url = result["data"]["url"]
            print(url)
